package com.dj.product.k2faas.validator.datasource;

import com.dj.product.k2faas.common.enums.DataStatus;
import com.dj.product.k2faas.common.exception.BadRequestException;
import com.dj.product.k2faas.common.exception.ConflictException;
import com.dj.product.k2faas.common.exception.NotFoundException;
import com.dj.product.k2faas.view.datasource.DataSourceView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by 丁建 on 2025/9/23 09:28
 *
 * @author 丁建
 */
@Service
public class DataSourceValidator {

    @Autowired
    private DataSourceView dataSourceView;

    public void assertNameAvailable(String name) {
        try {
            dataSourceView.findByName(name);
            throw new ConflictException("数据源名称：%s已经被占用".formatted(name));
        } catch (NotFoundException ignored) {
        }
    }

    public void assertNameAvailable(long id, String name) {
        try {
            var ds = dataSourceView.findByName(name);
            if (ds.getId() == id) {
                return;
            }
            throw new ConflictException("数据源名称：%s已经被ID为：%s的数据源占用".formatted(name, ds.getId()));
        } catch (NotFoundException ignored) {

        }
    }

    public void assertDataSourceValid(long dataSourceId) {
        var ds = dataSourceView.findById(dataSourceId);
        if (ds.getStatus() != DataStatus.NORMAL) {
            throw new BadRequestException("数据源：%s已经处于：%s状态".formatted(dataSourceId, ds.getStatus()));
        }
    }
}
